/**
 * Created by claim on 16-12-11.
 */
const db = require('./../../model/index');
const helper = require('./../../helper/auth');
const responser = require('./../../lib/responser');
const sender = require('./../../lib/identifyCode');
const cache = require('./../../instance/cache');
const Check = require("../../lib/check.js").Check
const captcha = require("../../instance/geeCode")

module.exports = router => {
    router.get("/email/geecode", async (ctx) => {
        var data = await captcha.register({
            client_type: 'web',
            ip_address: `unknown`
        },function(err,data){
            if(err){
                throw err
            }

            if(!data.success){
                ctx.session.fallback = true;
            }else{
                ctx.session.fallback = false
            }
        });

        ctx.body = data;
    })

    router.post("/email/validate", async (ctx) => {
        Check(ctx,"email","geetest_challenge","geetest_validate","geetest_seccode")

        let body = ctx.request.body
        var email = body.email

        await captcha.validate(ctx.session.fallback, {

            geetest_challenge: body.geetest_challenge,
            geetest_validate: body.geetest_validate,
            geetest_seccode: body.geetest_seccode

        }, function (err, success) {

            if (err) {
                // 网络错误
                throw err

            } else if (!success) {

                // 二次验证失败
                responser.reject(ctx,"Code Err",401)

            } else {
                let code = sender.sendMail(email);
                cache.set(email, code);
                cache.expire(email, 300);
                responser.success(ctx, 'Message Sent')
            }

        });
    })

    router.post('/user/validate/email', async(ctx, next) => { //用邮件地址验证
        let body = ctx.request.body;
        let user;
        let error;
        if (body.email)
            user = await db.models.User.findOne({
                where: {
                    email: body.email
                }
            }).catch(err => {
                error = err;
            });
        else if (body.username)
            user = await db.models.User.findOne({
                where: {
                    username: body.username
                }
            }).catch(err => {
                error = err;
            });
        else if (body.mobile)
            user = await db.models.User.findOne({
                where: {
                    mobile: body.mobile
                }
            }).catch(err => {
                error = err;
            });
        else if (body.LoginToken) {
            let username = await helper.getUsername(body.LoginToken);
            user = await db.models.User.findOne({
                where: {
                    username: username
                }
            }).catch(err => {
                error = err;
            });
        }
        if (user) {
            let email = user.getDataValue("email");
            if (!email) {
                responser.reject(ctx, 'The user haven\'t a email address', 403);
                return null;
            }
            let current = await cache.get(email);
            if (!current) {
                let code = sender.sendMail(email);
                cache.set(email, code);
                cache.expire(email, 120);
                responser.success(ctx, 'Message Sent');
            } else {
                responser.reject(ctx, "The interval between transmissions is too short", 403);
            }
        } else {
            let errorInfo;
            if (error && /SequelizeUniqueConstraintError/.test(error.toString())) {
                errorInfo = 'User does not exist';
            }
            if (errorInfo)
                responser.reject(ctx, errorInfo, 403);
            else
                responser.catchErr(ctx, error, 500);
        }
        await next();
    });

    router.post('/user/validate/mobile', async(ctx, next) => { //用手机号码验证
        let body = ctx.request.body;
        let user;
        let error;
        if (body.email)
            user = await db.models.User.findOne({
                where: {
                    email: body.email
                }
            }).catch(err => {
                error = err;
            });
        else if (body.username)
            user = await db.models.User.findOne({
                where: {
                    username: body.username
                }
            }).catch(err => {
                error = err;
            });
        else if (body.mobile)
            user = await db.models.User.findOne({
                where: {
                    mobile: body.mobile
                }
            }).catch(err => {
                error = err;
            });
        else if (body.LoginToken) {
            let username = await helper.getUsername(body.LoginToken);
            user = await db.models.User.findOne({
                where: {
                    username: username
                }
            }).catch(err => {
                error = err;
            });
        }
        if (user) {
            let mobile = user.getDataValue("mobile");
            if (!mobile) {
                responser.reject(ctx, 'The user haven\'t a mobile number', 403);
                return null;
            }
            let current = await cache.get(mobile);
            if (!current) {
                let code = sender.sendTextMessage(mobile);
                cache.set(mobile, code);
                cache.expire(mobile, 120);
                responser.success(ctx, 'Message Sent');
            } else {
                responser.reject(ctx, "The interval between transmissions is too short", 403);
            }
        } else {
            let errorInfo;
            if (error && /SequelizeUniqueConstraintError/.test(error.toString())) {
                errorInfo = 'User does not exist';
            }
            if (errorInfo)
                responser.reject(ctx, errorInfo, 403);
            else
                responser.catchErr(ctx, error, 500);
        }
        await next();
    });
    //todo:If mobile is used
    //todo:If mail address is used
    //todo:Change info
    //todo:Check passed
};